﻿using System;
using System.Linq;
using SampleApp.Domain;
using SampleApp.Data;
using System.Collections.Generic;

namespace SampleApp.Service
{
    public class SysMenuService : ISysMenuService
    {
        private ISysMenuRepository sysMenuRepository;
        private IRuntimeService runtimeService;
        public SysMenuService(IRuntimeService runtimeService, ISysMenuRepository sysMenuRepository)
        {
            this.runtimeService = runtimeService;
            this.sysMenuRepository = sysMenuRepository;
        }

        /// <summary>
        /// 当前用户所属角色可见的菜单项
        /// </summary>
        /// <returns></returns>
        public List<SysMenu> GetCurrentUserSysMenuList()
        {
            var menuAll = this.sysMenuRepository.GetMany(i=>true).ToList();
            //当前用户有权限表中,取Action与menuID一致的功能项
            var menu = menuAll.Where(m => m.ParentMenuID != "root" && !string.IsNullOrEmpty(m.ParentMenuID)).Where(m => this.runtimeService.Permission.TryTestAllowPermissionItem("Action:" + m.Url))
                    .Select(m => m);
            var parent = menuAll.Where(m=>menu.Any(child=>child.ParentMenuID == m.MenuID)).ToList();
            return menu.Concat(parent).ToList();
        }


        public SysMenu GetSysMenuByID(string sysMenuID)
        {
            return this.sysMenuRepository.GetByID(sysMenuID);
        }

        public void CreateSysMenu(SysMenu sysMenu)
        {
            this.sysMenuRepository.Add(sysMenu);
            this.runtimeService.UnitOfWork.Commit();
        }


        public void DeleteSysMenu(string sysMenuID)
        {
            var menu = this.GetSysMenuByID(sysMenuID);
            this.sysMenuRepository.Delete(menu);
            this.runtimeService.UnitOfWork.Commit();
        }


        public void UpdateSysMenu(SysMenu sysMenu)
        {
            var exists = this.GetSysMenuByID(sysMenu.MenuID);
            this.sysMenuRepository.SetValues(sysMenu, exists);
            this.runtimeService.UnitOfWork.Commit();
        }

        /// <summary>
        /// 仅载入子菜单
        /// </summary>
        /// <param name="parentMenuID"></param>
        /// <returns></returns>
        public List<SysMenu> GetSysMenuListByParent(string parentMenuID)
        {
            if (string.IsNullOrEmpty(parentMenuID))
                parentMenuID = "root";
            return this.sysMenuRepository.GetMany(i => i.ParentMenuID == parentMenuID).ToList();
        }

        public List<SysMenu> GetSysMenuList()
        {
            return this.sysMenuRepository.GetMany(i => true).ToList();
        }

    }
}
